package br.fatec.ads.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.fatec.ads.dao.LoginDAO;
import br.fatec.ads.exception.DataBaseException;
import br.fatec.ads.exception.LoginException;
import br.fatec.ads.model.Usuario;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LoginDAO loginDAO = new LoginDAO();
		
		Usuario usu = new Usuario();
		usu.setLogin(request.getParameter("txtLoginUsuario"));
		usu.setSenha(request.getParameter("txtLoginSenha"));
		
		try {
			Usuario usuario = new Usuario();
			usuario = loginDAO.loginUsuario(usu);
			
			if(usuario.getLogin() != null && !usuario.getLogin().equals("") && usuario.getAtivo().equals("S")){
				HttpSession session = request.getSession(true);  
		        session.setAttribute("idUsuario", usuario.getIdUsuario());
		        session.setAttribute("usuarioDesc", usuario.getLogin());
		        session.setAttribute("usuarioAtivo", usuario.getAtivo().equals("S"));
		        session.setAttribute("tipoUsuario", usuario.getTipoUsuario());
		        if(usuario.getTipoUsuario().equals("A")){
		        	session.setAttribute("menuSistema", "menu_administrador.jsp");
		        } else if(usuario.getTipoUsuario().equals("R")){
		        	session.setAttribute("menuSistema", "menu_recrutador.jsp");
		        } else{
		        	session.setAttribute("menuSistema", "menu_usuario.jsp");
		        }
		        request.getRequestDispatcher("index.jsp").forward(request, response);
			}else if(usuario.getLogin() != null && !usuario.getLogin().equals("") && !usuario.getAtivo().equals("S")){
				request.setAttribute("usuarioLogin", usu);
				request.getRequestDispatcher("login.jsp?acao=inativo").forward(request, response);
			}else if(usuario.getLogin() == null){
				request.setAttribute("usuarioLogin", usu);
				request.getRequestDispatcher("login.jsp?acao=naoexiste").forward(request, response);
			}
		} catch (LoginException e) {
			request.setAttribute("usuarioLogin", usu);
			request.getRequestDispatcher("login.jsp?acao=erro&descricao=" + e.getMessage()).forward(request, response);
			e.printStackTrace();
		} catch (DataBaseException e) {
			request.setAttribute("usuarioLogin", usu);
			request.getRequestDispatcher("login.jsp?acao=erro&descricao=" + e.getMessage()).forward(request, response);
			e.printStackTrace();
		}
	}

}
